//
//  BankLocationsViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/11/28.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import MapKit

class BankLocationsViewController: KMViewController {
    
    fileprivate var bankName = ""
    
    fileprivate var latitude:Double = 0 //经度
    fileprivate var longitude:Double = 0 //纬度
    fileprivate var city = "" //城市
    
    fileprivate var page = 1 //页数
    
    fileprivate var model = BankDetailsModel() //当前大头针信息
    
    fileprivate var mapView : MAMapView! //地图
    fileprivate let search = AMapSearchAPI()
    fileprivate let locationManager = AMapLocationManager()
    
    let footView = BankLocationsFooterView()
    
    //更多银行
    fileprivate lazy var moreBankView : MoreBankView = {
      
        let moreBankView = MoreBankView.init(frame: self.view.bounds)
        moreBankView.delegate = self
        moreBankView.isHidden = true
        self.view.addSubview(moreBankView)
        return moreBankView
        
    }()
    
    init(bankName:String) {
        super.init(nibName: nil, bundle: nil)
        
        self.bankName = bankName
        
        self.title = near + self.bankName + outlets
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        createRightButton()
        getCurrrentLocation()
        showMAp()
    }
    
    //MARK: 右键
    fileprivate func createRightButton() {
        
        let barButton = UIBarButtonItem.init(image: UIImage.init(named: "details"), style: .done, target: self, action: #selector(showMoreBank))
        self.navigationItem.rightBarButtonItem = barButton
    }
    
    //MARK: 显示更多银行
    @objc fileprivate func showMoreBank() {
        
        if self.footView.model == nil {
            return
        }
        
        moreBankView.isHidden = !moreBankView.isHidden
    }
    
    //MARK: 获取当前位置
    fileprivate func getCurrrentLocation() {
        
        locationManager.desiredAccuracy = kCLLocationAccuracyBest //设置精准度
        locationManager.locationTimeout = 2 //定位超时
        locationManager.reGeocodeTimeout = 2 //逆地址超时
        locationManager.requestLocation(withReGeocode: false) { [weak self](location, reGeocode, error) in
            
            let code  = (error as NSError?)?.code
            
            if code == AMapLocationErrorCode.locateFailed.rawValue {
                KMTool.showText(_text: (error?.localizedDescription)!)
                return
            }else if code == AMapLocationErrorCode.reGeocodeFailed.rawValue || code == AMapLocationErrorCode.timeOut.rawValue || code == AMapLocationErrorCode.cannotFindHost.rawValue || code == AMapLocationErrorCode.badURL.rawValue || code == AMapLocationErrorCode.notConnectedToInternet.rawValue || code == AMapLocationErrorCode.cannotConnectToHost.rawValue {
                
                KMTool.showText(_text: (error?.localizedDescription)!)
                
            }else{
                
                MyLog(location?.coordinate)
                if location == nil {
                    return
                }
                let geocoder = CLGeocoder()
                geocoder.reverseGeocodeLocation(location!, completionHandler: { (array, error) in
                    if array != nil && (array?.count)! > 0 {
                        let placemark = array?.first
                        //获取城市
                        var city = placemark?.locality
                        if city != nil {
                            MyLog(city)
                            MyLog(placemark?.name)
                            MyLog(placemark?.subLocality)
                            MyLog(placemark?.country)
                            MyLog(placemark?.administrativeArea)
                        }else{
                            city = placemark?.administrativeArea
                            MyLog(city)
                            MyLog(placemark?.name)
                            MyLog(placemark?.subLocality)
                            MyLog(placemark?.country)
                            MyLog(placemark?.administrativeArea)
                        }
                        
                        self?.latitude = (location?.coordinate.latitude)!
                        self?.longitude = (location?.coordinate.longitude)!
                        self?.city = city!
                        self?.searchBuild(latitude: (self?.latitude)!, longitude: (self?.longitude)!, city: (self?.city)!)
                    }
                })
                
            }
            
            
            
        }
    }
    
    //MARK: 加载地图
    fileprivate func showMAp() {
        
        mapView = MAMapView.init(frame: self.view.bounds)
        mapView.zoomLevel = 15 //缩放级别
        mapView.delegate = self
        mapView.showsUserLocation = true //定位到当前位置
        mapView.userTrackingMode = .follow //显示当前位置标记
        mapView.showsCompass = false //不显示指南针
        
        self.view.addSubview(mapView)
        
        //定位当前位置蓝点
        let userLocation = MAUserLocationRepresentation()
        //定位点背景颜色
        userLocation.locationDotBgColor = UIColor.clear
        //不显示动画
        userLocation.enablePulseAnnimation = false
        //刷新
        mapView.update(userLocation)
        
        footView.isHidden = true
        footView.goButton.addTarget(self, action: #selector(goHereAction), for: .touchUpInside)
        footView.nameButton.addTarget(self, action: #selector(changeFootFrame), for: .touchUpInside)
        self.view.addSubview(footView)
        
        footView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 150))
            make.bottom.equalToSuperview().offset(RATIO_H(maxNum: 100))
        }
    }
    
    //MARK: 修改尾部坐标
    @objc fileprivate func changeFootFrame() {
        
        footView.isFlag = !footView.isFlag
        
        if footView.isFlag {
            footView.snp.remakeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.height.equalTo(RATIO_H(maxNum: 150))
                make.bottom.equalToSuperview()
            }
        }else{
            footView.snp.remakeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.height.equalTo(RATIO_H(maxNum: 150))
                make.bottom.equalToSuperview().offset(RATIO_H(maxNum: 100))
            }
        }
    }
    
    //MARK: 去这里
    @objc fileprivate func goHereAction() {
        
        let mapVC = BankMapViewController.init(startLatitude: CGFloat(self.latitude), startLongitude: CGFloat(self.longitude), model: footView.model)
        self.navigationController?.pushViewController(mapVC, animated: true)
    }
    
    //MARK: 获取指定建筑物
    fileprivate func searchBuild(latitude:Double,longitude:Double,city:String) {
        
        search?.delegate = self
        
        let request = AMapPOIAroundSearchRequest()
        
        request.offset = 30 //加载的条数
        request.radius = 20000 //搜索范围(m)
        request.page = self.page
        request.keywords = self.bankName
        request.city = city
        request.requireExtension = true
        request.location = AMapGeoPoint.location(withLatitude: CGFloat(latitude), longitude: CGFloat(longitude))
        search?.aMapPOIAroundSearch(request)
    }
    

}

extension BankLocationsViewController : MAMapViewDelegate {
    
    //MARK: 添加大头针
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        
        if annotation.isKind(of: MAUserLocation.self) {
            return nil
        }
        
        if annotation.isKind(of: MAPointAnnotation.self)
        {
            
            let pointReuseIndetifier = "pointReuseIndetifier"
            var annotationView: MAAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: pointReuseIndetifier)
            
            if annotationView == nil {
                annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: pointReuseIndetifier)
                
            }
            
            annotationView!.image = nil
            annotationView!.canShowCallout = false
            annotationView!.isDraggable = false
            
            if annotation.title == self.footView.model.name {
                annotationView!.image = UIImage(named: "currentBank_location")
            }else if annotation.title == self.model.name {
                annotationView!.image = UIImage(named: "bank_location")
            }

            
            return annotationView
        }
        
        return nil
    }
    
    //MARK: 点击大头针
    func mapView(_ mapView: MAMapView!, didSelect view: MAAnnotationView!) {
        
        for model in self.moreBankView.dataArray {
            if view.annotation.title == model.name {
                self.selectBankName(model: model)
                return
            }
        }
    }
    
}

extension BankLocationsViewController : AMapSearchDelegate {
    
    func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) {
        
        KMTool.showText(_text: searchFail)
        
    }
    
    func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
        
        if response.pois.count == 0 {
            KMTool.showText(_text: notAboutNews)
            return
        }
        
        
        for poi in response.pois {
            
            let model = BankDetailsModel()
            model.name = poi.name
            model.address = poi.address
            model.distance = poi.distance
            model.type = poi.type
            model.latitude = poi.location.latitude
            model.longitude = poi.location.longitude
            model.city = poi.city
            model.tel = poi.tel
            
            
            MyLog("\(poi.name ?? ""),\(poi.address ?? ""),\(poi.distance),\(poi.type ?? ""),\(poi.tel ?? "")")
            
            //信息过滤
            
            if poi.name.contains(bankName) && !poi.name.contains(parkingLot) {
                self.moreBankView.dataArray.append(model)
            }
            
            footView.isHidden = false
            footView.model = self.moreBankView.dataArray.first
            self.moreBankView.tableView.reloadData()
        }
        
        for model in self.moreBankView.dataArray {
            
            self.model = model
            
            let destinationCoordinate = CLLocationCoordinate2DMake(CLLocationDegrees(model.latitude!), CLLocationDegrees(model.longitude!))
            
            //添加大头针标注
            let annod = MAPointAnnotation()
            annod.coordinate = destinationCoordinate
            annod.title = model.name
            annod.subtitle = (model.address ?? "") + "\n" + (model.tel ?? "")
            mapView.addAnnotation(annod)
        }
        
        
    }
    
}

extension BankLocationsViewController : MoreBankViewDelegate {
    
    //MAKR: 选择银行
    func selectBankName(model: BankDetailsModel) {
        
        //移除大头针
        mapView.removeOverlays(mapView.overlays)
        mapView.removeAnnotations(mapView.annotations)
        
        self.footView.model = model
        moreBankView.isHidden = true
        
        for model in self.moreBankView.dataArray {

            self.model = model

            let destinationCoordinate = CLLocationCoordinate2DMake(CLLocationDegrees(model.latitude!), CLLocationDegrees(model.longitude!))

            //添加大头针标注
            let annod = MAPointAnnotation()
            annod.coordinate = destinationCoordinate
            annod.title = model.name
            annod.subtitle = (model.address ?? "") + "\n" + (model.tel ?? "")
            mapView.addAnnotation(annod)
        }
    }
    
    
}
